import { useEffect, useState } from 'react'

export const isFalsy: (value: unknown) => boolean = (value) =>
	value === 0 ? false : !value

// 在一个函数里，尽量不要改变传入的对象
export const cleanObject = (object: object) => {
	const result = { ...object }
	Object.keys(result).forEach((key) => {
		// @ts-ignore
		const value = result[key]
		if (isFalsy(value)) {
			// @ts-ignore
			delete result[key]
		}
	})

	return result
}

// custom hook 自定义hook，首次加载调用函数
export const useMount = (callback: () => void) => {
	useEffect((...params) => {
		callback(...params)
	// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [])
}

/**
 * 将value 转化为 debouncedValue, 使用泛型来规范类型
 * @param {} value 需要debounce的param
 * @param {*} delay
 */
export const useDebounce = <V>(value: V, delay?: number) => {
	// 定义一个状态，状态在react中是响应式的
	const [debouncedValue, setDebouncedValue] = useState(value)

	useEffect(() => {
		const timeout = setTimeout(() => setDebouncedValue(value), delay)
		return () => clearTimeout(timeout)
	}, [value, delay])

	return debouncedValue
}
